import axios from "axios";
import { Toast } from "vant";
import Vue from "vue";
import router from "@/router";
// 处理loading
const toast = () =>
  Toast.loading({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    loadingType: "spinner",
    className: "loading-icon",
    message: "加载中..."
  });

const instance = axios.create({
  baseURL: "http://47.108.151.34:9989", // 如果配置代理就用这个
  timeout: 3500
});

// 创建请求拦截
instance.interceptors.request.use(
  config => {
    toast();
    const token = Vue.ls.get("token")
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config;
  },
  error => {
    Toast.clear();
    Promise.reject(error);
  }
);

// 创建响应拦截
instance.interceptors.response.use(
  response => {
    const data = response.data || {};
    Toast.clear();
    // 根据code判断
    if (data.code === 200) {
      return Promise.resolve(data);
    } else if (data.code === 401) {
      data.msg &&
        Toast({
          message: data.msg,
          duration: 5200
        });
      router.replace("/login")
      Vue.ls.clear()
    } else {
      data.msg &&
        Toast({
          message: data.msg,
          duration: 5200
        });
    }
  },
  error => {
    Toast.clear();
    return Promise.reject(error);
  }
);

export default instance;
